package com.ruoyi.web.controller.circle;

import java.util.List;

import com.ruoyi.file.utils.FileOperateUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.circle.domain.CircleMemberRelation;
import com.ruoyi.circle.service.ICircleMemberRelationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 圈子成员关系Controller
 *
 * @author 区嘉盛
 */
@RestController
@RequestMapping("/circle/member")
@Tag(name = "【圈子成员关系】管理")
public class CircleMemberRelationController extends BaseController {
    @Autowired
    private ICircleMemberRelationService circleMemberRelationService;

    /**
     * 查询圈子成员关系列表
     */
    @Operation(summary = "查询圈子成员关系列表")
    @GetMapping("/list")
    public TableDataInfo list(CircleMemberRelation circleMemberRelation) {
        startPage();
        List<CircleMemberRelation> list = circleMemberRelationService.selectCircleMemberRelationList(circleMemberRelation);
        return getDataTable(list);
    }

    /**
     * 查询圈子成员列表（包含用户信息）
     */
    @Operation(summary = "查询圈子成员列表")
    @GetMapping("/memberList/{circleId}")
    public TableDataInfo memberList(@PathVariable("circleId") Long circleId) {
        startPage();
        CircleMemberRelation circleMemberRelation = new CircleMemberRelation();
        circleMemberRelation.setCircleId(circleId);
//        circleMemberRelation.setMemberStatus(1);
        List<CircleMemberRelation> list = circleMemberRelationService.selectCircleMemberList(circleMemberRelation);
//        for (CircleMemberRelation memberRelation : list) {
//            if (memberRelation.getAvatar() != null) {
//                try {
//                    memberRelation.setAvatar(FileOperateUtils.getURL(memberRelation.getAvatar()));
//                } catch (Exception e) {
//                }
//            }
//        }
        return getDataTable(list);
    }

    /**
     * 导出圈子基础信息列表
     */
    @Operation(summary = "导出圈子成员关系列表")
    @Log(title = "圈子成员关系", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CircleMemberRelation circleMemberRelation) {
        List<CircleMemberRelation> list = circleMemberRelationService.selectCircleMemberRelationList(circleMemberRelation);
        ExcelUtil<CircleMemberRelation> util = new ExcelUtil<CircleMemberRelation>(CircleMemberRelation.class);
        util.exportExcel(response, list, "圈子成员关系数据");
    }

    /**
     * 获取当前用户在圈子中的角色
     */
    @Operation(summary = "获取当前用户在圈子中的角色")
    @GetMapping(value = "/currentUserRole/{circleId}")
    public AjaxResult getCurrentUserRole(@PathVariable("circleId") Long circleId) {
        Long userId = getUserId();
        Integer role = circleMemberRelationService.selectUserRoleInCircle(circleId, userId);
        return success(role);
    }

    /**
     * 获取圈子成员关系详细信息
     */
    @Operation(summary = "获取圈子成员关系详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(circleMemberRelationService.selectCircleMemberRelationById(id));
    }

    /**
     * 查询用户在圈子中的角色
     */
    @Operation(summary = "查询用户在圈子中的角色")
    @GetMapping(value = "/role/{circleId}/{userId}")
    public AjaxResult getUserRole(@PathVariable("circleId") Long circleId, @PathVariable("userId") Long userId) {
        return success(circleMemberRelationService.selectUserRoleInCircle(circleId, userId));
    }

    /**
     * 新增圈子成员关系
     */
    @Operation(summary = "新增圈子成员关系")
    @Log(title = "圈子成员关系", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CircleMemberRelation circleMemberRelation) {
        return toAjax(circleMemberRelationService.insertCircleMemberRelation(circleMemberRelation));
    }

    /**
     * 添加圈子成员
     */
    @Operation(summary = "添加圈子成员")
    @Log(title = "圈子成员关系", businessType = BusinessType.INSERT)
    @PostMapping("/add/{circleId}/{userId}/{memberRole}")
    public AjaxResult addMember(@PathVariable("circleId") Long circleId,
                                @PathVariable("userId") Long userId,
                                @PathVariable("memberRole") Integer memberRole) {
        return toAjax(circleMemberRelationService.addCircleMember(circleId, userId, memberRole));
    }

    /**
     * 修改圈子成员关系
     */
    @Operation(summary = "修改圈子成员关系")
    @Log(title = "圈子成员关系", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CircleMemberRelation circleMemberRelation) {
        return toAjax(circleMemberRelationService.updateCircleMemberRelation(circleMemberRelation));
    }

    /**
     * 更新圈子成员角色
     */
    @Operation(summary = "更新圈子成员角色")
    @Log(title = "圈子成员关系", businessType = BusinessType.UPDATE)
    @PutMapping("/role")
    public AjaxResult updateRoleByBody(@RequestBody CircleMemberRelation circleMemberRelation) {
        return toAjax(circleMemberRelationService.updateMemberRole(
                circleMemberRelation.getCircleId(),
                circleMemberRelation.getUserId(),
                circleMemberRelation.getMemberRole()));
    }

    /**
     * 删除圈子成员关系
     */
    @Operation(summary = "删除圈子成员关系")
    @Log(title = "圈子成员关系", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(circleMemberRelationService.deleteCircleMemberRelationByIds(ids));
    }

    /**
     * 移除圈子成员
     */
    @Operation(summary = "移除圈子成员")
    @Log(title = "圈子成员关系", businessType = BusinessType.UPDATE)
    @DeleteMapping("/remove/{circleId}/{userId}")
    public AjaxResult removeMember(@PathVariable("circleId") Long circleId, @PathVariable("userId") Long userId) {
        return toAjax(circleMemberRelationService.removeCircleMember(circleId, userId));
    }

    /**
     * 普通用户加入圈子
     */
    @Operation(summary = "普通用户加入圈子")
    @Log(title = "用户加入圈子", businessType = BusinessType.INSERT)
    @PostMapping("/join/{circleId}")
    public AjaxResult joinCircle(@PathVariable("circleId") Long circleId) {
        Long userId = getUserId();
        return toAjax(circleMemberRelationService.joinCircle(circleId, userId));
    }

    /**
     * 普通用户退出圈子
     */
    @Operation(summary = "普通用户退出圈子")
    @Log(title = "用户退出圈子", businessType = BusinessType.UPDATE)
    @PostMapping("/leave/{circleId}")
    public AjaxResult leaveCircle(@PathVariable("circleId") Long circleId) {
        Long userId = getUserId();
        return toAjax(circleMemberRelationService.leaveCircle(circleId, userId));
    }

    /**
     * 设置用户黑名单状态
     */
    @Operation(summary = "设置用户黑名单状态")
    @Log(title = "圈子成员黑名单", businessType = BusinessType.UPDATE)
    @PutMapping("/blacklist/{circleId}/{userId}/{status}")
    public AjaxResult updateBlacklistStatus(
            @PathVariable("circleId") Long circleId,
            @PathVariable("userId") Long userId,
            @PathVariable("status") Integer status) {
        return toAjax(circleMemberRelationService.updateBlacklistStatus(circleId, userId, status));
    }

    /**
     * 查询用户是否在黑名单中
     */
    @Operation(summary = "查询用户是否在黑名单中")
    @GetMapping("/blacklist/{circleId}/{userId}")
    public AjaxResult checkUserInBlacklist(
            @PathVariable("circleId") Long circleId,
            @PathVariable("userId") Long userId) {
        return success(circleMemberRelationService.checkUserInBlacklist(circleId, userId));
    }

    /**
     * 查询圈子黑名单列表
     */
    @Operation(summary = "查询圈子黑名单列表")
    @GetMapping("/blacklist/list/{circleId}")
    public TableDataInfo blacklistList(@PathVariable("circleId") Long circleId) {
        startPage();
        CircleMemberRelation circleMemberRelation = new CircleMemberRelation();
        circleMemberRelation.setCircleId(circleId);
        circleMemberRelation.setBlacklistStatus(1);
        List<CircleMemberRelation> list = circleMemberRelationService.selectCircleMemberList(circleMemberRelation);
        return getDataTable(list);
    }

    /**
     * 转让圈主
     */
    @Operation(summary = "转让圈主")
    @Log(title = "转让圈主", businessType = BusinessType.UPDATE)
    @PutMapping("/owner/{circleId}/{userId}/{newOwnerName}")
    public AjaxResult updateTransferOwner(
            @PathVariable("circleId") Long circleId,
            @PathVariable("userId") Long userId,
            @PathVariable("newOwnerName") String newOwnerName) {
        logger.info("转让圈主 circleId: {}, userId: {}, newOwnerName: {}", circleId, userId, newOwnerName);
        Long orderOwnerId = getUserId();
        return toAjax(circleMemberRelationService.updateTransferOwner(circleId, userId, orderOwnerId,newOwnerName,getUsername()));
    }
}